import pandas as pd
# import reverse_geocoder as rg
# from rg__init__ import *
# from rg__init__ import search
from regeocoder import *
# import regeocoder as ag
import re
import sys
import os.path
import time

def progress_bar(finish_tasks_number, tasks_number, complete_time):
    """
    进度条

    :param finish_tasks_number: int, 已完成的任务数
    :param tasks_number: int, 总的任务数
    :param complete_time: float, 已完成的任务所消耗的总时间
    :return:
    """

    percentage = round(finish_tasks_number / tasks_number * 100)
    finished_label = "*" * (percentage // 2)#▓"
    unfinished_label = "-" * (100 - percentage)
    arrow = "->"
    if not finished_label or not unfinished_label:
        arrow = ""
    print("\r{}% [{}{}{}] {:.2f}s".format(percentage, finished_label, arrow, unfinished_label, complete_time), end="")

def str_float(string):
    a = re.findall("-?\d+.?\d+",string)  # 正则表达式
    b = list(map(float,a))
    lon=b[0]
    lat=b[1]
    return lon,lat

def re_geocode(lat,lon):
    coordinates = (lat,lon)
    # results = rg.search(coordinates) # default mode = 2
    results = search(coordinates)  # default mode = 2
    address=results[0]['cc1']+'('+results[0]['cc']+')'+'_'+results[0]['admin1']+'_'+results[0]['name']
    return address

def return_str(leftup,rightdown):
    leftup_lon,leftup_lat=str_float(leftup)
    leftup_address=re_geocode(leftup_lat,leftup_lon)
    rightdown_lon,rightdown_lat=str_float(rightdown)
    rightdown_address=re_geocode(rightdown_lat,rightdown_lon)
#     string='右下角'+rightdown_address
    string='左上角:'+leftup_address+';'+'右下角:'+rightdown_address
    return string

def reverse_geocoder(inputfilepath):
    # inputfilepath=r'C:\Users\ran\Desktop\excel\GF1CD_0801-0831.xlsx'
    dfc1=pd.read_excel(inputfilepath)
    leftup=dfc1['左上角坐标']
    rightdown=dfc1['右下角坐标']
    weizhi=[]
    start = time.perf_counter()
    if os.path.exists(rel_path('./rg_cities1000.csv')):
        print('Loading formatted geocoded file...')
        for i in range(0,dfc1.shape[0]):#dfc1.shape[0]):
            duration = time.perf_counter() - start
            try:
                # print(i)
                progress_bar(i, dfc1.shape[0] - 1, duration)
                weizhi.append(str(return_str(leftup[i],rightdown[i])))
            except:
                weizhi.append('error')
    else:
        print('The formatted geocoded file losed!')
        os._exit(0)
    dfc1['位置']=weizhi
    basename = os.path.basename(inputfilepath).split('.')[0]+'_weizhi.xlsx'
    dirname = os.path.dirname(inputfilepath)
    outputfilepath=str(os.path.join(dirname,basename))
    dfc1.to_excel(outputfilepath,index=False)
    # dfc1.to_excel(r'C:\Users\ran\Desktop\excel\GF1C_dir0801.xlsx',sheet_name='GF1C_dir0801-0815_lonti')
if __name__ == "__main__":
    # reverse_geocoder(r'D:\Master\internship\reverse_geocoder\8月位置gf2-副本.xlsx')
    reverse_geocoder(sys.argv[1])


